package com.example.counter1;

import java.util.Stack;
public class ExpressionEvaluator {
    public static double evaluate(String expression) {
        expression = expression.replaceAll("\\s+", "");
        Stack<Double> numbers = new Stack<>();
        Stack<Character> ops = new Stack<>();
        int i = 0;
        while (i < expression.length()) {
            char c = expression.charAt(i);
            if (Character.isDigit(c) || c == '.') {
                // 解析数字
                StringBuilder num = new StringBuilder();
                while (i < expression.length() &&
                        (Character.isDigit(expression.charAt(i)) || expression.charAt(i) == '.')) {
                    num.append(expression.charAt(i++));
                }
                numbers.push(Double.parseDouble(num.toString()));
            } else if (c == '(') {
                ops.push(c);
                i++;
            } else if (c == ')') {
                while (ops.peek() != '(') {
                    applyOp(numbers, ops.pop());
                }
                ops.pop(); // 弹出 '('
                i++;
            } else if (isOperator(c)) {
                // 处理负号（单目运算符）
                if (c == '-' && (i == 0 || expression.charAt(i-1) == '(' ||
                        isOperator(expression.charAt(i-1)))) {
                    numbers.push(0.0);
                }
                // 处理运算符优先级
                while (!ops.isEmpty() && precedence(ops.peek()) >= precedence(c)) {
                    applyOp(numbers, ops.pop());
                }
                ops.push(c);
                i++;
            } else {
                throw new IllegalArgumentException("无效字符: " + c);
            }
        }
        // 处理剩余运算符
        while (!ops.isEmpty()) {
            applyOp(numbers, ops.pop());
        }
        return numbers.pop();
    }

    private static boolean isOperator(char c) {
        return c == '+' || c == '-' || c == '*' || c == '/';
    }

    private static int precedence(char op) {
        switch (op) {
            case '+': case '-': return 1;
            case '*': case '/': return 2;
            default: return 0; // 括号
        }
    }

    private static void applyOp(Stack<Double> nums, char op) {
        double b = nums.pop();
        double a = nums.isEmpty() ? 0 : nums.pop();
        switch (op) {
            case '+': nums.push(a + b); break;
            case '-': nums.push(a - b); break;
            case '*': nums.push(a * b); break;
            case '/':
                if (b == 0) throw new ArithmeticException("除零错误");
                nums.push(a / b);
                break;
        }
    }

    public static void main(String[] args) {
        String expr = "(3+5)*2";
        System.out.println(evaluate(expr)); // 输出 16.0
    }
}
